package com.untrance.shop.web.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.images.Image;
import com.untrance.shop.core.service.ImageService;

/**
 * @author eugene zadyra
 */
@Controller
public class ImageController {

	private static Logger log = LoggerFactory.getLogger(ImageController.class);

	@Autowired
	ImageService imageService;

	@RequestMapping("/image.html")
	public ModelAndView getImage(HttpServletResponse response,
			@RequestParam(value = "id", required = false) Long id) {
		log.debug("Image: " + id);
		if (id!=null) {
			try {
				Key key = KeyFactory.createKey(Image.class.getSimpleName(), id);
				byte[] image = imageService.getImageByKey(key);
				if (image == null) {
					return CommonController.forward404;
				}
				response.getOutputStream().write(image);
				response.flushBuffer();
				return null;
			} catch (IOException e) {
				log.warn(e.getMessage(), e);
			}
		}
		return CommonController.forward404;
	}

	@RequestMapping("/upload-image.html")
	public ModelAndView uploadImage(@RequestParam(value = "file", required = false) CommonsMultipartFile file) {
		if (file != null && !file.isEmpty()) {
			imageService.saveImage(file.getName(), file.getBytes());
			return new ModelAndView("redirect:/images/" + file.getName());
		}
		return null;
	}
}
